package com.szh.gulimall.cart.interceptor;

import com.szh.common.constant.AuthServerConstant;
import com.szh.common.constant.CartConstant;
import com.szh.common.vo.MemberResponseVo;
import com.szh.gulimall.cart.vo.UserInfoTo;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Objects;
import java.util.UUID;

/**
 * 购物车拦截器
 * 在执行目标方法之前，判断用户的登录状态，并封装传递给controller目标请求
 *
 * @author: SongZiHao
 * @date: 2023/1/16
 */
public class CartInterceptor implements HandlerInterceptor {

    public static ThreadLocal<UserInfoTo> threadLocal = new ThreadLocal<>();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        UserInfoTo userInfoTo = new UserInfoTo();
        HttpSession session = request.getSession();
        MemberResponseVo member = (MemberResponseVo) session.getAttribute(AuthServerConstant.SESSION_KEY);
        if (Objects.nonNull(member)) { //用户登录了
            userInfoTo.setUserId(member.getId());
        }
        Cookie[] cookies = request.getCookies();
        if (cookies != null && cookies.length > 0) {
            for (Cookie cookie : cookies) {
                String name = cookie.getName();
                if (name.equals(CartConstant.TEMP_USER_COOKIE_NAME)) {
                    userInfoTo.setUserKey(cookie.getValue());
                    userInfoTo.setTempUser(true);
                }
            }
        }
        //如果没有临时用户，则分配一个临时用户的user-key
        if (StringUtils.isEmpty(userInfoTo.getUserKey())) {
            String uuid = UUID.randomUUID().toString();
            userInfoTo.setUserKey(uuid);
        }
        //拦截器放行之前，将UserInfoTo信息放入ThreadLocal，保证多个线程可以共享UserInfoTo
        threadLocal.set(userInfoTo);
        return true;
    }

    /**
     * 浏览器有一个cookie：user-key，标识用户身份，一个月之后过期
     * 如果第一次使用购物车功能，都会给一个临时的用户身份，浏览器以后保存，每次访问呢都会带上这个cookie
     *
     * 在目标方法执行之后，如果没有临时用户信息，则将临时用户的信息存入cookie中
     * cookie放大作用域为gulimall.com，设置过期时间为一个月
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        UserInfoTo userInfoTo = threadLocal.get();
        if (!userInfoTo.isTempUser()) {
            Cookie cookie = new Cookie(CartConstant.TEMP_USER_COOKIE_NAME, userInfoTo.getUserKey());
            cookie.setDomain("gulimall.com");
            cookie.setMaxAge(CartConstant.TEMP_USER_COOKIE_TIMEOUT);
            response.addCookie(cookie);
        }
    }
}
